package com.bobo.controller;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bobo.auth.common.JWTUtils;
import com.bobo.auth.common.Result;
import com.bobo.domain.SysMenu;
import com.bobo.domain.SysRoleMenu;
import com.bobo.service.SysMenuService;
import com.bobo.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("menu")
@RestController
public class MenuController {
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    SysRoleMenuService sysRoleMenuService;


    /**
     * 删除菜单
     * @param id
     * @return
     */
    @RequestMapping("delById")
    public Result delById(Integer id){
        boolean b = sysMenuService.removeById(id);
        return b?Result.success():Result.fail();
    }



    @RequestMapping("getMenuByPid")
    public Result getMenuByPid(Integer id){
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMenu::getParentId,id);
        List<SysMenu> list = sysMenuService.list(wrapper);
        return list.size()>0?Result.fail():Result.success();
    }


    /**
     *
     * @param sysMenu
     * @return
     */
    @RequestMapping("saveOrUpdate")
    public  Result saveOrUpdate(@RequestBody SysMenu sysMenu){
        boolean b=sysMenuService.saveOrUpdate(sysMenu);
        return b?Result.success():Result.fail();

    }


    @RequestMapping("list")
    public Result list() {
        String username = JWTUtils.getUsername();//从请求的头中获取用户名
        List<Tree<String>> treeMenu = sysMenuService.getTreeMenu(username);
        return Result.success(treeMenu);
    }


    /**
     * 根据角色获取菜单id
     * @param rid
     * @return
     */
    @RequestMapping("getMidsByRid")
    public Result getMidsByRid(Integer rid){
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRid,rid);
        List<SysRoleMenu> list = sysRoleMenuService.list(wrapper);
        ArrayList<Integer> mids = new ArrayList<>();
        if(null!=list && list.size()>0){
            for (SysRoleMenu sysRoleMenu : list) {
                mids.add(sysRoleMenu.getMid());
            }
        }

        return Result.success(mids);
    }
}
